<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/img/16x16.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/img/32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/img/16x16.png">
  <link rel="mask-icon" href="/img/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free@6.3.0/css/all.min.css" integrity="sha256-/4UQcSmErDzPCMAiuOiWPVVsNN2s3ZY/NsmXNcj0IFc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"lirifa.github.io","root":"/","images":"/images","scheme":"Mist","darkmode":true,"version":"8.15.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"bookmark":{"enable":true,"color":"#2bb5d4","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"livere","storage":true,"lazyload":false,"nav":null,"activeClass":"livere"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="JavaScript的继承机制基于原型链，它定义了对象属性和方法的查找规则。每个对象都有一个原型，通过原型链，对象能访问到构造函数原型上的方法。">
<meta property="og:type" content="article">
<meta property="og:title" content="js中的原型与原型链">
<meta property="og:url" content="https://lirifa.github.io/js%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.html">
<meta property="og:site_name" content="Rafa&#39;s Blog">
<meta property="og:description" content="JavaScript的继承机制基于原型链，它定义了对象属性和方法的查找规则。每个对象都有一个原型，通过原型链，对象能访问到构造函数原型上的方法。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s21.ax1x.com/2025/11/25/pZA3HhV.png">
<meta property="og:image" content="https://s21.ax1x.com/2025/11/25/pZA8DvF.png">
<meta property="og:image" content="https://s21.ax1x.com/2025/11/25/pZAGTzT.png">
<meta property="article:published_time" content="2021-03-10T08:23:33.000Z">
<meta property="article:modified_time" content="2021-03-10T08:23:33.000Z">
<meta property="article:author" content="Rafa">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s21.ax1x.com/2025/11/25/pZA3HhV.png">


<link rel="canonical" href="https://lirifa.github.io/js%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://lirifa.github.io/js%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.html","path":"js中的原型与原型链.html","title":"js中的原型与原型链"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>js中的原型与原型链 | Rafa's Blog</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?e65b95711a0ae7fa2a5d53e3186cff24"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Rafa's Blog</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">角落</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-留言"><a href="/guestbook/" rel="section"><i class="fa fa-book fa-fw"></i>留言</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E5%9F%BA%E7%A1%80"><span class="nav-text">原型基础</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E9%93%BE%E7%9A%84%E5%BD%A2%E6%88%90"><span class="nav-text">原型链的形成</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BF%AE%E6%94%B9%E5%8E%9F%E5%9E%8B%E7%9A%84%E5%BD%B1%E5%93%8D"><span class="nav-text">修改原型的影响</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E9%93%BE%E7%9A%84%E5%B0%BD%E5%A4%B4"><span class="nav-text">原型链的尽头</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88null%E6%A0%87%E5%BF%97%E7%9D%80%E7%BB%93%E6%9D%9F%EF%BC%9F"><span class="nav-text">为什么null标志着结束？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AE%9E%E9%99%85%E6%84%8F%E4%B9%89"><span class="nav-text">实际意义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BB%A7%E6%89%BF%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="nav-text">继承的实现方式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%8E%9F%E5%9E%8B%E9%93%BE%E7%BB%A7%E6%89%BF"><span class="nav-text">1. 原型链继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E7%BB%A7%E6%89%BF"><span class="nav-text">2. 构造函数继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%BB%84%E5%90%88%E7%BB%A7%E6%89%BF%EF%BC%88%E7%BB%8F%E5%85%B8%E7%BB%A7%E6%89%BF%EF%BC%89"><span class="nav-text">3. 组合继承（经典继承）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ES6-Class%E7%BB%A7%E6%89%BF"><span class="nav-text">ES6 Class继承</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AE%9E%E6%88%98%E7%A4%BA%E4%BE%8B%EF%BC%9A%E5%88%9B%E5%BB%BA%E5%8F%AF%E6%89%A9%E5%B1%95%E7%9A%84%E5%8A%A8%E7%89%A9%E7%8E%8B%E5%9B%BD"><span class="nav-text">实战示例：创建可扩展的动物王国</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Rafa"
      src="https://avatars.githubusercontent.com/u/44889418?v=4">
  <p class="site-author-name" itemprop="name">Rafa</p>
  <div class="site-description" itemprop="description">角落</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">10</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/lirifa" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lirifa" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:rafa_im@163.com" title="E-Mail → mailto:rafa_im@163.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lirifa.github.io/js%E4%B8%AD%E7%9A%84%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/44889418?v=4">
      <meta itemprop="name" content="Rafa">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Rafa's Blog">
      <meta itemprop="description" content="角落">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="js中的原型与原型链 | Rafa's Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js中的原型与原型链
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-03-10 16:23:33" itemprop="dateCreated datePublished" datetime="2021-03-10T16:23:33+08:00">2021-03-10</time>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>11k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>10 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p> JavaScript的继承机制基于原型链，它定义了对象属性和方法的查找规则。每个对象都有一个原型，通过原型链，对象能访问到构造函数原型上的方法。<br> <a id="more"></a></p>
<h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p> 在深入探索JavaScript编程的旅程中，理解继承机制是攀登至高技能水平的关键一步。作为这门语言的基石之一，继承不仅支撑着代码的复用性和模块化的实现，还深刻影响着对象间关系的构建与数据结构的设计。其中，原型链扮演着核心角色，它定义了对象属性和方法的查找规则，串联起JavaScript对象的血缘与能力传承。</p>
<h1 id="原型基础"><a href="#原型基础" class="headerlink" title="原型基础"></a>原型基础</h1><p> 首先，每个JavaScript对象都有一个内置的属性叫做[[Prototype]]，通常通过__proto__访问（非标准但广泛支持），它指向创建该对象的构造函数的prototype属性。构造函数的prototype本身也是一个对象，拥有自己的属性和方法。<br> <figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Animal.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;I am an animal&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> cat = <span class="keyword">new</span> Animal(<span class="string">&#x27;Kitty&#x27;</span>); <span class="comment">// 创建Animal的实例</span></span><br><span class="line"><span class="built_in">console</span>.log(cat);</span><br><span class="line"><span class="built_in">console</span>.log(cat.__proto__ === Animal.prototype)</span><br><span class="line">cat.speak();</span><br></pre></td></tr></table></figure><br> 在这里，cat的__proto__指向Animal.prototype，这意味着cat可以访问Animal.prototype上的方法，如speak。<br> <a target="_blank" rel="noopener" href="https://imgchr.com/i/pZA3HhV"><img src="https://s21.ax1x.com/2025/11/25/pZA3HhV.png" alt="pZA3HhV.png"></a></p>
<h1 id="原型链的形成"><a href="#原型链的形成" class="headerlink" title="原型链的形成"></a>原型链的形成</h1><p>当试图访问一个对象的属性或方法时，如果该对象本身没有定义，JavaScript引擎会向上查找其原型（__proto__指向的对象），这一过程会一直追溯到原型链的顶部，通常是Object.prototype。如果在那里还找不到，就会返回undefined。<br><a target="_blank" rel="noopener" href="https://imgchr.com/i/pZA8DvF"><img src="https://s21.ax1x.com/2025/11/25/pZA8DvF.png" alt="pZA8DvF.png"></a><br>图中蓝色的链路及为我们常说的原型链</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(cat.speak === Animal.prototype.speak); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>这行代码确认了cat实例的speak方法确实是指向Animal.prototype上的speak方法，证实了继承关系的存在。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cat.speak(); <span class="comment">// 输出: &quot;I am an animal&quot;</span></span><br></pre></td></tr></table></figure>
<p>调用cat.speak()成功执行并打印出”I am an animal”，这证明了cat实例能够正确地沿原型链访问到Animal.prototype上定义的speak方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(cat.toString()); <span class="comment">// 输出：[object Object]</span></span><br></pre></td></tr></table></figure>
<p>尽管在Animal构造函数或其原型上没有直接定义toString方法，cat.toString()仍然能够执行并按预期工作。这是因为所有JavaScript对象（除非被特殊修改）都默认从Object.prototype继承了toString方法。toString方法通常用于返回对象的字符串表示，对于普通的对象实例，默认情况下返回的是”[object Object]”。</p>
<blockquote>
<p>原型链是JavaScript实现继承的核心机制，它允许对象间接访问其原型链上定义的属性和方法，直至达到Object.prototype。这一机制不仅简化了代码复用，也是理解JavaScript面向对象编程的关键。通过上述示例，我们可以看到即便没有在每个对象或构造函数中显式定义所有方法，也可以通过原型链继承自上层原型或最终的Object.prototype，从而获得这些功能。</p>
</blockquote>
<h1 id="修改原型的影响"><a href="#修改原型的影响" class="headerlink" title="修改原型的影响"></a>修改原型的影响</h1><p>修改原型对象会影响所有通过该构造函数创建的实例。这是因为所有实例共享同一个原型对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Animal.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Now I can talk too!&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">cat.speak(); <span class="comment">// 输出变为 &quot;Now I can talk too!&quot;</span></span><br></pre></td></tr></table></figure>
<p>这里，我们修改了Animal.prototype上的speak方法，所有Animal的实例调用speak时都会反映出这一变化。</p>
<p>由于修改原型会影响到所有通过该构造函数创建的实例，开发中应当谨慎操作，以防止原型污染。一种常见做法是使用不可变（Immutable）的设计模式，或者在必要时为每个实例单独添加方法，而不是修改原型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">giveUniqueVoice</span>(<span class="params">animal, voice</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">    animal.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;   </span><br><span class="line">        <span class="built_in">console</span>.log(voice);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> specialCat = <span class="keyword">new</span> Animal(<span class="string">&#x27;Whiskers&#x27;</span>);</span><br><span class="line">giveUniqueVoice(specialCat, <span class="string">&#x27;Meow!&#x27;</span>);</span><br><span class="line"></span><br><span class="line">specialCat.speak(); <span class="comment">// 输出 &quot;Meow!&quot;</span></span><br><span class="line">cat.speak(); <span class="comment">// 输出 &quot;My behavior has been changed!&quot;</span></span><br></pre></td></tr></table></figure>
<p>在这个例子中，我们通过giveUniqueVoice函数为特定实例specialCat添加了一个独特的speak方法，这样做不会影响到其他Animal实例的行为。</p>
<h1 id="原型链的尽头"><a href="#原型链的尽头" class="headerlink" title="原型链的尽头"></a>原型链的尽头</h1><p>原型链的尽头，指的是JavaScript中对象原型链层级结构的最终点，这个终点是null。在JavaScript中，每个对象（除null外）都有一个内部属性称为[[Prototype]]，它指向创建该对象的原型对象。这个原型对象本身也可能是一个对象，同样拥有自己的[[Prototype]]，如此形成了所谓的原型链。</p>
<blockquote>
<p>当我们尝试访问一个对象的属性或方法时，如果在该对象自身找不到，JavaScript引擎会继续在其原型对象中查找，即沿着原型链向上遍历。这一过程会一直持续到遇到一个原型对象的[[Prototype]]为null的点，这标志着原型链的终点。换句话说，null作为原型链的终点，表示没有更进一步的原型可以继承或查找。</p>
</blockquote>
<p>如下代码所示</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">    name = <span class="string">&#x27;Animal&#x27;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">speak</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;I am an animal&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name); </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(myDog)</span><br></pre></td></tr></table></figure>
<p><a target="_blank" rel="noopener" href="https://imgchr.com/i/pZAGTzT"><img src="https://s21.ax1x.com/2025/11/25/pZAGTzT.png" alt="pZAGTzT.png"></a></p>
<ol>
<li>myDog (Dog实例):</li>
</ol>
<ul>
<li>直接属性：name = ‘Wancai’，这是因为在Dog类的构造函数中，通过super(name)调用了父类Animal的构造函数，并将’Wancai’作为参数传递，从而设置了实例的name属性。</li>
<li>内部属性[[Prototype]]指向Dog.prototype。</li>
</ul>
<ol start="2">
<li>Dog.prototype:</li>
</ol>
<ul>
<li>这是Dog类的原型对象，默认包含一个constructor属性指向Dog构造函数自身。</li>
<li>内部属性[[Prototype]]指向Animal.prototype，因为Dog类通过extends  Animal继承了Animal类，所以其原型链会链接到Animal类的原型对象。</li>
</ul>
<ol start="3">
<li>Animal.prototype:</li>
</ol>
<ul>
<li>包含了Animal类定义的方法，如speak()。</li>
<li>内部属性[[Prototype]]指向Object.prototype，这是所有JavaScript对象原型链的标准终点前一站，表明Animal类的原型也是基于基础的JavaScript对象构建的。</li>
</ul>
<ol start="4">
<li>Object.prototype:</li>
</ol>
<ul>
<li>这是所有JavaScript对象的原型链最终到达的地方，包含了像toString(), valueOf()等基本方法。</li>
<li>内部属性[[Prototype]]为null，标志着原型链的终点。</li>
</ul>
<p>综上所述，myDog的原型链路径如下：</p>
<ul>
<li>myDog -&gt; Dog.prototype -&gt; Animal.prototype -&gt; Object.prototype -&gt; null</li>
</ul>
<p>这条链展示了从myDog实例出发，逐级向上通过原型链查找属性和方法的过程，直到抵达null，即原型链的顶层。</p>
<h1 id="为什么null标志着结束？"><a href="#为什么null标志着结束？" class="headerlink" title="为什么null标志着结束？"></a>为什么null标志着结束？</h1><p>null作为Object.prototype的[[ Prototype ]]，是一个特意的设计选择，它表示这条原型链到此为止，没有更进一步的原型可供查找。null既不是对象也不是函数，它是一种特殊的值，用来表示空值或者尚未赋值的状态。在原型链上下文中，它起到了终止链式查找的作用，防止无限循环查找。</p>
<h1 id="实际意义"><a href="#实际意义" class="headerlink" title="实际意义"></a>实际意义</h1><p>理解原型链的这一终端特性，对开发者来说有几个重要含义：</p>
<ol>
<li><strong>性能考量：</strong>它确保了属性查找有一个明确的终点，避免了无止境的循环搜索，从而优化了访问速度。</li>
<li><strong>对象基础：</strong>揭示了所有对象共享的基本行为，强调了JavaScript中一切皆对象的原则，即使是null这样的特殊值也是对象行为逻辑的一部分。</li>
<li><strong>继承体系的清晰度：</strong>有助于开发者构建清晰的继承结构，知道何时应该直接在对象上定义方法，何时通过原型链继承，以及如何避免无意中修改基础对象的行为。</li>
</ol>
<p>原型链的尽头指向Object.prototype，其[[Prototype]]为null，这一设计精巧地构建了JavaScript对象继承的基础框架。掌握这一概念，对于深入理解对象间的继承关系、避免常见的原型链错误，以及高效地设计和维护代码结构都是至关重要的。它是通往JavaScript高级编程之路上的一块基石。</p>
<hr>
<h1 id="继承的实现方式"><a href="#继承的实现方式" class="headerlink" title="继承的实现方式"></a>继承的实现方式</h1><h2 id="1-原型链继承"><a href="#1-原型链继承" class="headerlink" title="1. 原型链继承"></a>1. 原型链继承</h2><p>最直接的继承方式就是通过原型链。上面的例子已经展示了这一点，但我们可以更明确地设置原型链：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Animal.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;I am an animal&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用Animal的prototype作为Dog.prototype的原型</span></span><br><span class="line">Dog.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br><span class="line">Dog.prototype.constructor = Dog; <span class="comment">// 修复constructor指向</span></span><br><span class="line"></span><br><span class="line">Dog.prototype.bark = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Woof!&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line">myDog.speak(); <span class="comment">// I am an animal</span></span><br><span class="line">myDog.bark(); <span class="comment">// Woof!</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>这段代码展示了如何使用原型链继承在JavaScript中实现继承。这里是逐步解析：</p>
<ul>
<li><p>定义子类构造函数 Dog:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">  </span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Dog 构造函数接收一个参数 name，并将其作为实例的 name 属性。</p>
</li>
<li><p>设置 Dog.prototype 的原型为 Animal.prototype 的副本:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Dog.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br></pre></td></tr></table></figure>
<p>这行代码是关键，它使用 Object.create 方法创建了 Animal.prototype 的一个新对象，然后将其赋值给 Dog.prototype。这样一来，所有通过 Dog 构造函数创建的实例都会在其原型链上找到 Animal.prototype，从而继承了 Animal 的属性和方法。</p>
</li>
<li><p>修复 constructor 指向:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Dog.prototype.constructor = Dog;</span><br></pre></td></tr></table></figure>
<p>由于我们直接改变了 Dog.prototype 的指向，原本指向 Dog 的 constructor 现在会指向 Animal。为了修正这一点，我们需要手动将其设置回 Dog。</p>
</li>
<li><p>在 Dog.prototype 上定义 bark 方法:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Dog.prototype.bark = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    </span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;Woof!&#x27;</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>这为 Dog 的实例添加了一个独有的方法 bark。</p>
</li>
<li><p>创建 Dog 的实例并测试:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line">myDog.speak(); <span class="comment">// 输出 &quot;I am an animal&quot;</span></span><br><span class="line">myDog.bark(); <span class="comment">// 输出 &quot;Woof!&quot;</span></span><br></pre></td></tr></table></figure>
<p>通过 new Dog(‘Wangcai’) 创建了一个名为 “Wangcai” 的狗实例。由于 Dog.prototype 指向了 Animal.prototype 的副本，myDog 可以访问到 Animal 上的 speak 方法。同时，它也有自己特有的 bark 方法。</p>
</li>
</ul>
<p>综上所述，这段代码演示了如何利用原型链实现JavaScript中的继承，让子类能够复用父类的属性和方法，同时也能够扩展自己的特性。</p>
<ul>
<li>特点：简单直接，通过将子类型的原型指向父类型的实例，实现方法的继承。</li>
<li>优点：易于实现，节省内存（共享方法）。</li>
<li>缺点：父类的引用类型属性会被所有子类实例共享；无法在构造函数中向父类传递参数。</li>
</ul>
<h2 id="2-构造函数继承"><a href="#2-构造函数继承" class="headerlink" title="2. 构造函数继承"></a>2. 构造函数继承</h2><p>另一种方式是通过在子类构造函数内部调用超类构造函数，这种方式不涉及原型链，而是直接复制属性。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    Animal.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.species = <span class="string">&#x27;Canine&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(myDog.name); <span class="comment">// Wangcai</span></span><br><span class="line"><span class="built_in">console</span>.log(myDog.species); <span class="comment">// Canine</span></span><br></pre></td></tr></table></figure>
<p>这段代码展示了构造函数继承的方式实现JavaScript中的继承。下面是详细的解析：</p>
<ul>
<li><p>定义子类构造函数 Dog:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">     </span><br><span class="line">     </span><br><span class="line">    Animal.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.species = <span class="string">&#x27;Canine&#x27;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 Dog 构造函数内部，通过 Animal.call(this, name) 调用了 Animal 构造函数。这里的 call 方法改变了 Animal 内部 this 的指向，使其指向当前 Dog 实例，从而使得 Dog 实例能够继承 Animal 的属性。这就是构造函数继承的核心所在。<br>接着，Dog 构造函数还定义了自己的属性 species，设置为 ‘Canine’。</p>
</li>
<li><p>创建 Dog 实例并检查属性:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(myDog.name); <span class="comment">// 输出 &quot;Wangcai&quot;</span></span><br><span class="line"><span class="built_in">console</span>.log(myDog.species); <span class="comment">// 输出 &quot;Canine&quot;</span></span><br></pre></td></tr></table></figure>
<p>通过 new Dog(‘Wangcai’) 创建了一个 Dog 的实例，并传入名字 ‘Wangcai’。由于在 Dog 构造函数中调用了 Animal.call(this, name)，myDog 实例继承了 Animal 的 name 属性，值为 ‘Wangcai’。同时，myDog 实例还有自己特有的属性 species，值为 ‘Canine’。</p>
</li>
</ul>
<p>总结来说，这段代码演示了如何通过在子类构造函数内部手动调用父类构造函数（并使用 call 或 apply 方法绑定正确的 this 上下文）来实现继承，这种方式允许子类继承父类的属性，同时可以扩展自己的属性和方法。</p>
<ul>
<li><strong>特点：</strong>通过在子类构造函数内部调用父类构造函数，实现属性的继承。</li>
<li><strong>优点：</strong>每个实例都有自己的属性副本，解决了原型链继承中的属性共享问题。</li>
<li><strong>缺点：</strong>只能继承属性，无法继承方法；每次实例化都会创建方法的新副本，浪费内存。</li>
</ul>
<h2 id="3-组合继承（经典继承）"><a href="#3-组合继承（经典继承）" class="headerlink" title="3. 组合继承（经典继承）"></a>3. 组合继承（经典继承）</h2><p>结合原型链继承和构造函数继承，是最常用的继承模式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Animal.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;I am an animal&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    Animal.call(<span class="built_in">this</span>, name);</span><br><span class="line">    <span class="built_in">this</span>.species = <span class="string">&#x27;Canine&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用Animal的prototype作为Dog.prototype的原型</span></span><br><span class="line">Dog.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br><span class="line">Dog.prototype.constructor = Dog;</span><br><span class="line"></span><br><span class="line">Dog.prototype.bark = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Woof!&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line">myDog.speak(); <span class="comment">// I am an animal</span></span><br><span class="line">myDog.bark(); <span class="comment">// Woof!</span></span><br><span class="line"><span class="built_in">console</span>.log(myDog.species); <span class="comment">// Canine</span></span><br></pre></td></tr></table></figure>
<p>这段代码展示了JavaScript中的一种继承模式，结合了构造函数继承和原型链继承（也称作组合继承），这种组合继承方式综合了构造函数继承和原型链继承的优点，既能够继承实例属性，又能有效复用方法，是JavaScript中较为完善的继承实现方式之一。</p>
<ul>
<li><strong>特点：</strong>结合了原型链继承和构造函数继承的优点，是最常用的继承模式。</li>
<li><strong>优点：</strong>既能继承属性也能继承方法，且每个实例都有自己的属性副本，同时方法又是共享的。</li>
<li><strong>缺点：</strong>构造函数中调用了两次父类构造函数（一次在子类构造函数内部，一次在原型链设定时），稍微有些冗余。</li>
</ul>
<h2 id="ES6-Class继承"><a href="#ES6-Class继承" class="headerlink" title="ES6 Class继承"></a>ES6 Class继承</h2><p>ES6引入了基于class的语法糖，使得继承更加清晰易懂。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义基类 Animal:</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line"><span class="comment">// Animal 类通过 constructor 方法定义了一个构造器，用于初始化 name 属性，并定义了一个 speak 方法。</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line">   </span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">speak</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">   </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;I am an animal&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义子类 Dog 继承 Animal</span></span><br><span class="line"><span class="comment">// extends 关键字表明 Dog 类继承自 Animal 类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line"><span class="comment">// 在 Dog 的构造函数中，super(name) 调用了父类的构造函数，传递了参数 name，这是继承父类属性的关键步骤</span></span><br><span class="line">        <span class="built_in">super</span>(name); <span class="comment">// 调用父类构造函数</span></span><br><span class="line">        <span class="built_in">this</span>.species = <span class="string">&#x27;Canine&#x27;</span>; <span class="comment">// 定义了 Dog 特有的属性 species</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 定义了 Dog 特有的方法 bark。</span></span><br><span class="line">    <span class="function"><span class="title">bark</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">   </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Woof!&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line">myDog.speak(); <span class="comment">// I am an animal</span></span><br><span class="line">myDog.bark(); <span class="comment">// Woof!</span></span><br><span class="line"><span class="built_in">console</span>.log(myDog.species); <span class="comment">// Canine</span></span><br></pre></td></tr></table></figure>

<p>使用 class 语法实现继承简化了传统构造函数和原型链的复杂性，提供了更接近于其他面向对象语言的继承模型，使得代码更加清晰和易于理解。</p>
<ul>
<li><strong>特点：</strong>引入了面向对象编程中的class语法，使得继承的语义更加清晰，更接近其他面向对象语言。</li>
<li><strong>优点：</strong>语法简洁，易于理解，支持静态方法和类属性，提高了代码的可读性和可维护性。</li>
<li><strong>缺点：</strong>本质上仍然是基于原型，只是语法糖，新手可能会误解为传统的类继承模型。<blockquote>
<p>每种继承方式的选择应根据实际项目需求和团队习惯来决定。在ES6及以后的版本中，推荐使用class语法进行继承，它不仅代码更加优雅，而且更易于理解和维护。然而，理解背后的基本原理——原型链和构造函数——对于深入掌握JavaScript的面向对象编程是至关重要的。</p>
</blockquote>
</li>
</ul>
<h1 id="实战示例：创建可扩展的动物王国"><a href="#实战示例：创建可扩展的动物王国" class="headerlink" title="实战示例：创建可扩展的动物王国"></a>实战示例：创建可扩展的动物王国</h1><ol>
<li>基础动物类 (Animal)<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 定义基础动物构造函数，接收一个name参数初始化动物名字</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Animal</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">this</span>.name = name; <span class="comment">// 使用this关键字将传入的name赋值给新创建对象的name属性</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在Animal的原型对象上定义一个speak方法，模拟动物发出声音</span></span><br><span class="line">Animal.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Some generic sound&#x27;</span>); <span class="comment">// 打印通用的声音文本</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></li>
<li>具体动物类 (Dog &amp; Cat)<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Dog构造函数，继承Animal</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dog</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    Animal.call(<span class="built_in">this</span>, name); <span class="comment">// 使用Animal.call调用超类构造函数，确保name属性被正确初始化</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置Dog的原型为Animal的原型的一个新对象实例，实现继承</span></span><br><span class="line">Dog.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br><span class="line"><span class="comment">// 修复构造函数指针，确保构造函数引用正确</span></span><br><span class="line">Dog.prototype.constructor = Dog;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 覆盖speak方法，使Dog有特定的叫声</span></span><br><span class="line">Dog.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Woof!&#x27;</span>); <span class="comment">// 打印Dog的叫声</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 类似的操作创建Cat类</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Cat</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    Animal.call(<span class="built_in">this</span>, name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Cat.prototype = <span class="built_in">Object</span>.create(Animal.prototype);</span><br><span class="line">Cat.prototype.constructor = Cat;</span><br><span class="line"></span><br><span class="line">Cat.prototype.speak = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Meow!&#x27;</span>); <span class="comment">// 打印Cat的叫声</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></li>
<li>实际应用<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建Dog和Cat的实例</span></span><br><span class="line"><span class="keyword">const</span> myDog = <span class="keyword">new</span> Dog(<span class="string">&#x27;Wangcai&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> myCat = <span class="keyword">new</span> Cat(<span class="string">&#x27;Whiskers&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用各自的speak方法</span></span><br><span class="line">myDog.speak(); <span class="comment">// 输出: Woof!</span></span><br><span class="line">myCat.speak(); <span class="comment">// 输出: Meow!</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 动态添加行为到Animal原型，所有子类实例都能访问</span></span><br><span class="line">Animal.prototype.sleep = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;<span class="built_in">this</span>.name&#125;</span> is sleeping.`</span>); <span class="comment">// 打印睡觉信息，使用模板字符串插入实例的名字</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用新添加的sleep方法</span></span><br><span class="line">myDog.sleep(); <span class="comment">// 输出: Wangcai is sleeping.</span></span><br><span class="line">myCat.sleep(); <span class="comment">// 输出: Whiskers is sleeping.</span></span><br></pre></td></tr></table></figure>
这个示例演示了如何利用原型链实现继承，保持代码的灵活性和扩展性。通过Object.create方法建立原型链关系，确保了子类能够访问父类的属性和方法，同时也能够覆盖或添加新方法以实现特有行为。动物王国的模拟展示了多态性，即不同对象对同一消息（如speak）做出不同响应的能力，以及代码的可维护性和扩展性。</li>
</ol>
<hr>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>全面解析了JavaScript中的继承机制，核心围绕原型链这一核心概念展开，阐述了其在对象继承中的作用与重要性，并介绍了几种主要的继承实现方式。以下是文章内容的概括：</p>
<p>📌 原型基础</p>
<ul>
<li>每个JavaScript对象都隐含一个[[Prototype]]属性，通常通过__proto__访问，指向创建它的构造函数的prototype对象。</li>
<li>构造函数的prototype本身是个对象，包含可被实例共享的方法和属性。</li>
<li>示例展示了如何通过原型链，实例能访问到构造函数原型上的方法。</li>
</ul>
<p>📌 原型链的形成与查找规则</p>
<ul>
<li>当访问对象的属性或方法时，若对象自身未定义，则会沿其原型链向上查找，直至Object.prototype，最后到null终止。</li>
<li>解释了所有对象共享Object.prototype上的基本方法，如toString()等。</li>
</ul>
<p>📌 修改原型的影响</p>
<ul>
<li>修改原型对象会影响所有通过该构造函数创建的实例，因它们共享同一原型。</li>
<li>强调需谨慎修改原型以防“原型污染”，建议采用不可变模式或针对实例单独添加方法。</li>
</ul>
<p>📌 原型链的尽头</p>
<ul>
<li>深入探讨了Object.prototype的[[Prototype]]为null的意义，作为原型链的终点，保证了查找过程的终止。</li>
</ul>
<p>📌 继承的实现方式</p>
<ul>
<li><strong>原型链继承：</strong>直接设置子类型的原型为父类型的实例，简单直接，共享方法，但需注意构造函数的修正。</li>
<li><strong>构造函数继承：</strong>子类构造函数内部调用父类构造函数，实现属性继承，但不继承方法且方法不共享。</li>
<li><strong>组合继承：</strong>结合上述两者，最常用，既继承属性也继承方法，但构造函数被调用两次。</li>
<li><strong>ES6 Class继承：</strong>引入class语法，简化继承表达，提供更清晰的面向对象编程风格，本质仍是基于原型。</li>
</ul>
<p>每种继承方式都有其适用场景与优缺点，理解这些机制有助于开发者根据具体需求选择合适的继承策略，提升代码的效率与可维护性。文章强调了深入理解原型链与构造函数原理对于掌握JavaScript面向对象编程的重要性。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"><i class="fa fa-tag"></i> 前端</a>
              <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/js%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0%E3%80%81%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0.html" rel="prev" title="js手写系列——节流函数、防抖函数">
                  <i class="fa fa-chevron-left"></i> js手写系列——节流函数、防抖函数
                </a>
            </div>
            <div class="post-nav-item">
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="lv-container" data-id="city" data-uid="MTAyMC82MDk1Ni8zNzQyNg=="></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Rafa</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">38k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">34 分钟</span>
  </span>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="100" alpha="0.3" zIndex="-1" src="https://unpkg.com/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://unpkg.com/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/jquery@3.6.3/dist/jquery.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  <script src="https://unpkg.com/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>



  <script src="/js/third-party/fancybox.js"></script>


  




<script src="/js/third-party/comments/livere.js"></script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"left","width":160,"height":280},"mobile":{"show":false},"react":{"opacityDefault":1,"opacityOnHover":1},"log":false,"tagMode":false});</script></body>
</html>
